package com.hc.controller;

import com.hc.service.IAuthorizationService;
import com.hc.service.IMenuService;
import com.hc.util.Constant;
import com.hc.vo.RefreshTokenVO;
import com.hc.vo.StatusVO;
import com.hc.vo.UserNamePasswordVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {


    @Resource
    IAuthorizationService service;

    @Resource
    IMenuService menuService;


    @PostMapping("/login")
    @ApiOperation(value = "登录接口", produces = MediaType.APPLICATION_JSON_VALUE, response = StatusVO.class)
    public StatusVO doLogin(@RequestBody @Valid UserNamePasswordVO vo, Errors errors, HttpServletRequest request) {
        if (errors.hasErrors()) {
            return new StatusVO(400, "用户名或密码错误");
        }
        return new StatusVO(service.doLogin(vo.getUsername(), vo.getPassword(), request.getRemoteAddr()));
    }

    @PostMapping("/token")
    @ApiOperation(value = "刷新token接口", notes = "token放在data字段中,成功时code=200", produces = MediaType.APPLICATION_JSON_VALUE, response = StatusVO.class)
    public StatusVO tryRefresh(@RequestBody @Valid RefreshTokenVO vo, Errors errors) {
        if (errors.hasErrors()) {
            return new StatusVO(400, "必须包含token字段");
        }
        IAuthorizationService.TokenStatus status = service.verifyToken(vo.getToken());
        if (status == IAuthorizationService.TokenStatus.REFRESH) {
            return new StatusVO(200, "", service.refreshToken(vo.getToken()));
        } else if (status == IAuthorizationService.TokenStatus.INVALID) {
            return new StatusVO(Constant.TOKEN_EXPIRED);
        }
        //没过期的话只原样返回一个token
        return new StatusVO(200, "", vo.getToken());
    }


    @PostMapping("/community")
    public StatusVO getUserCommunityId(@RequestBody RefreshTokenVO vo) {
        return new StatusVO(service.getCommunityId(vo.getToken()));
    }


    @GetMapping("/menu")
    public StatusVO getMenu(@RequestHeader(Constant.AUTTH_HEADER_NAME) String token) {
        return new StatusVO(menuService.getAll());
    }
}
